package com.example.xyxwebbackend001.controller;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.StpUtil;
import com.example.xyxwebbackend001.common.CommonResult;
import com.example.xyxwebbackend001.config.FileUploadConfig;
import com.example.xyxwebbackend001.model.DTO.UserDTO;
import com.example.xyxwebbackend001.model.entity.User;
import com.example.xyxwebbackend001.service.EmailService;
import com.example.xyxwebbackend001.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/auth/")
public class AuthController {
    @Autowired
    private UserService userService;

    @Autowired
    private FileUploadConfig fileUploadConfig;

    @Autowired
    private EmailService emailService;

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @RequestMapping("doLogin")
    public CommonResult<Object> doLogin(@RequestBody Map<String, String> credentials) {
        try {
            String username = credentials.get("username");
            String password = credentials.get("password");

            if(username == null || password == null) {
                return CommonResult.fail(400, "用户名和密码不能为空");
            }
            UserDTO user = userService.authUser(username, password);

            if(user != null) {
                StpUtil.login(user.getUserId());
                return CommonResult.success(Map.of(
                        "user", Map.of(
                                "userId", user.getUserId(),
                                "username", user.getUsername(),
                                "email", user.getEmail(),
                                "avatarPath", user.getAvatarPath()
                        ),
                        "token", StpUtil.getTokenValue()
                ));
            }
            return CommonResult.fail(401, "用户名或密码错误");

        } catch (Exception e) {
            return CommonResult.error("系统异常：" + e.getMessage());
        }
    }

    @PostMapping("logout")
    public CommonResult<Object> logout() {
        userService.logout();
        return CommonResult.tip("退出成功");
    }
    @GetMapping("auth")
    public CommonResult<Object> auth(@RequestHeader(value = "Authorization", required = false) String authHeader) {

        if(!StpUtil.isLogin()) {
            return CommonResult.fail(401, "未登录");
        }

        Integer userId = StpUtil.getLoginIdAsInt();

        List<String> roles = StpUtil.getRoleList();

        return CommonResult.success(Map.of(
                "roles", roles,
                "isLogin", true
        ));
    }
    @PostMapping("send-code")
    public ResponseEntity<String> sendCode(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        logger.info("Received email verification request for: {}", email);

        if (!email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$")) {
            logger.error("Invalid email format: {}", email);
            return ResponseEntity.badRequest().body("邮箱格式错误");
        }

        try {
            emailService.sendVerificationCode(email);
            return ResponseEntity.ok("验证码已发送");
        } catch (Exception e) {
            logger.error("Email sending failed for {}: {}", email, e.getMessage());
            return ResponseEntity.internalServerError().body("邮件发送失败");
        }
    }

    @PostMapping("checkUserName")
    public CommonResult<Object> checkUserName(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        boolean exists = userService.checkUsername(username);
        return CommonResult.success(exists);
    }

    @PostMapping("register")
    public CommonResult<Object> register(@RequestBody Map<String, String> request) {
        try {
            // 获取请求参数
            String username = request.get("username");
            String password = request.get("password");
            String email = request.get("email");
            String code = request.get("code");

            // 参数非空校验
            if (username == null || password == null || email == null || code == null) {
                return CommonResult.fail(400, "所有字段不能为空");
            }

            // 邮箱格式验证
            if (!email.matches("\\w+@\\w+\\.\\w+")) {
                return CommonResult.fail(400, "邮箱格式错误");
            }
            if (userService.checkEmailExists(email)) {
                return CommonResult.fail(400, "该邮箱已被注册");
            }

            // 验证码校验
            if (!emailService.validateCode(email, code)) {
                return CommonResult.fail(400, "验证码错误或已过期");
            }

            // 检查用户名是否已存在
            if (userService.checkUsername(username)) {
                return CommonResult.fail(400, "用户名已被占用");
            }

            User newUser = new User();
            newUser.setUsername(username);
            newUser.setPassword(password);
            newUser.setEmail(email);
            Integer userId = userService.createUser(newUser);

            String defaultDir = fileUploadConfig.getDefaultAvatarDir();
            String baseDir = fileUploadConfig.getUploadAvatarDir();
            File templateDir = new File(defaultDir);
            File userDir = new File(baseDir + "/" + userId);

            if (!userDir.exists()) {
                userDir.mkdirs();
                if (templateDir.exists()) {
                    copyDirectory(templateDir, userDir);
                }
            }

            return CommonResult.success("注册成功");

        } catch (Exception e) {
            return CommonResult.error("注册失败: " + e.getMessage());
        }
    }
    private void copyDirectory(File sourceDir, File targetDir) throws IOException {
        if (sourceDir.isDirectory()) {
            if (!targetDir.exists()) {
                targetDir.mkdir();
            }

            for (String file : sourceDir.list()) {
                File srcFile = new File(sourceDir, file);
                File destFile = new File(targetDir, file);
                copyDirectory(srcFile, destFile);
            }
        } else {
            Files.copy(sourceDir.toPath(), targetDir.toPath());
        }
    }


    @PostMapping("forget-password")
    public CommonResult<Object> forgetPassword(@RequestBody Map<String, String> request) {
        try {
            // 获取请求参数
            String email = request.get("email");
            String password = request.get("password");
            String code = request.get("code");
            if ( email == null || password == null || code == null) {
                return CommonResult.fail(400, "所有字段不能为空");
            }
            // 邮箱格式验证
            if (!email.matches("\\w+@\\w+\\.\\w+")) {
                return CommonResult.fail(400, "邮箱格式错误");
            }
            if (!emailService.validateCode(email, code)) {
                return CommonResult.fail(400, "验证码错误或已过期");
            }
            int result = userService.forgetPassword(email, password);
            if (result == 1) {
                return CommonResult.success("密码修改成功");
            }
            return CommonResult.fail(400, "密码修改失败");
        } catch (Exception e) {
            return CommonResult.error("密码修改失败: " + e.getMessage());
        }
    }
}
